package net.csdra.basis.service;

import net.csdra.basis.domain.UserBaseInterface;
import net.csdra.basis.service.CurrentUserInfo;
import net.csdra.user.domain.User;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * Created by msf on 2017/10/11.
 */
@Service
public class CurrentUserInfoImpl<T extends UserBaseInterface> implements CurrentUserInfo<T> {

    @Override
    public T set(T user) {
        user.setPassword("");
        List<SimpleGrantedAuthority> collect = user.getAuthoritys().stream().map(userAuthoritys -> {
            return new SimpleGrantedAuthority("ROLE_" + userAuthoritys);
        }).collect(Collectors.toList());
        Authentication authentication = new UsernamePasswordAuthenticationToken(user.getId(), user, collect);
        SecurityContextHolder.getContext().setAuthentication(authentication);
        return user;
    }

    @Override
    public T get() throws AccessDeniedException {
        try {
            //spring-boot-test时
//            Object credentials = SecurityContextHolder.getContext().getAuthentication().getCredentials();
//            User userForm = new ObjectMapper().readValue(credentials.toString(), User.class);

            //正式使用
            T userForm = (T) SecurityContextHolder.getContext().getAuthentication().getCredentials();
            return userForm;
        } catch (Exception e) {
            throw new AccessDeniedException("@需要登录");
        }
    }


}
